package com.netty.helper;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelGroupFuture;
import io.netty.channel.group.ChannelMatcher;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @author suzhen
 * @create 2018/7/12
 */
public class ChannelGroupHelper {
    /**
     * 以下类是用来存储访问的channle，
     * channelGroup的原型是set集合，
     * 保证channle的唯一，如需根据参数标注存储，
     * 可以使用currentHashMap来存储。
     */
    private static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public static ChannelGroup getGroup() {
        return group;
    }

    public static void add(Channel channel) {
        group.add(channel);
    }

    public static void remove(Channel channel) {
        group.remove(channel);
    }

    /**
     * 广播
     *
     * @param msg
     * @return
     */
    public static ChannelGroupFuture broadcast(Object msg) {
        for (Channel channel :  getGroup()){
            System.out.println(channel);
        }

        return group.writeAndFlush(msg);
    }

    /**
     * 广播
     *
     * @param msg
     * @param matcher
     * @return
     */
    public static ChannelGroupFuture broadcast(Object msg, ChannelMatcher matcher) {
        return group.writeAndFlush(msg, matcher);
    }

    public static ChannelGroup flush() {
        return group.flush();
    }

    /**
     * 丢弃无用连接
     *
     * @param channel
     * @return
     */
    public static boolean discard(Channel channel) {
        return group.remove(channel);
    }

    /**
     * 断开所有连接
     *
     * @return
     */
    public static ChannelGroupFuture disconnect() {
        return group.disconnect();
    }

    /**
     * 断开指定连接
     *
     * @param matcher
     * @return
     */
    public static ChannelGroupFuture disconnect(ChannelMatcher matcher) {
        return group.disconnect(matcher);
    }

    /**
     * @param channel
     * @return
     */
    public static boolean isExist(Channel channel) {
        return group.contains(channel);
    }

    public static int size() {
        return group.size();
    }
}
